<!DOCTYPE html>
<html lang="en">
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="common/include :: header('结算单明细列表')"/>
</head>
<body>
<div class="ui-layout-center">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">客户姓名：</label>
                            <label class="col-sm-6 control-label">[[${statement.customerName}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">联系方式：</label>
                            <label class="col-sm-6 control-label">[[${statement.customerPhone}]]</label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >

                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">车牌号码：</label>
                            <label class="col-sm-6 control-label">[[${statement.licensePlate}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">汽车类型：</label>
                            <label class="col-sm-6 control-label">[[${statement.carSeries}]]</label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">服务类型：</label>
                            <label class="col-sm-6 control-label">[[${@dict.getLabel('si_service_catalog',statement.serviceType)}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">到店时间：</label>
                            <label class="col-sm-6 control-label" th:text="${#dates.format(statement.actualArrivalTime, 'yyyy-MM-dd HH:mm')}"></label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">总消费金额：</label>
                            <label class="col-sm-6 control-label" id="totalAmount">[[${statement.totalAmount}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">实付价格：</label>
                            <label class="col-sm-6 control-label" id="actuallyPaid">[[${statement.totalAmount-statement.discountAmount}]]</label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">优惠价格：</label>
                            <input class="col-sm-6" type="number" id="discountAmount" onchange="disCountFun()" name="discountAmount" th:field="${statement.discountAmount}"/>
                        </div>
                    </div>
                </div>
            </div>

            <div class="btn-group-sm" id="myTool" role="group">
                <a class="btn btn-success" onclick="saveFun()" shiro:hasPermission="business:statement:add">
                    <i class="fa fa-plus"></i> 保存
                </a>
                <a class="btn btn-info" onclick="payFun()" shiro:hasPermission="business:statement:add">
                    <i class="fa fa-plus"></i> 确认支付
                </a>
            </div>

            <div class="col-sm-12 select-table table-striped">
                <table id="statementItemTable"></table>
            </div>
        </div>
    </div>
</div>
<div class="ui-layout-east">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="serviceItem-form">
                    <div class="select-list">
                        <ul>
                            <li>
                                名称：<input type="text" name="name"/>
                            </li>

                            <li>
                                是否套餐：
                                <select name="carPackageStatus" th:with="type=${@dict.getType('si_car_package')}">
                                    <option value="">所有</option>
                                    <option th:each="dict : ${type}" th:text="${dict.label}"
                                            th:value="${dict.value}"></option>
                                </select>
                            </li>
                            <li>
                                服务分类：
                                <select name="serviceCatalogStatus"
                                        th:with="type=${@dict.getType('si_service_catalog')}">
                                    <option value="">所有</option>
                                    <option th:each="dict : ${type}" th:text="${dict.label}"
                                            th:value="${dict.value}"></option>
                                </select>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                        class="fa fa-search"></i>&nbsp;搜索</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="col-sm-12 select-table table-striped">
                <table id="serviceItemTable"></table>
            </div>
        </div>
    </div>
</div>


<th:block th:include="common/include :: footer"/>
<th:block th:include="common/include :: layout-latest"/>
</body>
<script>
    $('body').layout({
        east__size: '30%',
    });

    $(function () {
        var statementId = [[${statement.id}]];
        var options = {
            toolbar: "myTool",
            id: "statementItemTable",
            uniqueId: "itemId",
            url: "/business/statementItem/query?statementId="+statementId,                        // 查询的url
            columns: [
                {
                    field: 'id',
                    title: '明细id',
                    visible: false                          // 隐藏
                },
                {
                    field: 'itemId',
                    title: '服务单项id',
                    visible: false                          // 隐藏
                },
                {
                    field: 'itemName',
                    title: '服务项名称',
                    sortable: true
                },

                {
                    field: 'itemPrice',
                    title: '服务的价格',
                    sortable: true
                },
                {
                    field: 'itemQuantity',
                    title: '购买数量',
                    sortable: true
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)"' +
                            ' onclick="addItem(\'' + row.itemId + '\')"><i class="fa fa-plus"></i></a>');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)"' +
                            ' onclick="decrItem(\'' + row.itemId + '\')"><i class="fa fa-minus"></i></a>');
                        return actions.join(' ');
                    }
                }]
        };
        $.table.init(options);
    });

    function payFun(){
        var statementId = [[${statement.id}]];
        $.modal.confirm("确定要支付吗?" ,function () {
            $.operate.get("/business/statementItem/pay?statementId=" + statementId);
        })
    }


    var prefix = ctx + "/business/serviceItem";
    $(function () {
        var options = {
            uniqueId: "id",
            id: "serviceItemTable",
            url: prefix + "/query?saleStatus=1",                        // 查询的url
            columns: [
                {
                    field: 'id',
                    title: '服务单项id',
                    visible: false                          // 隐藏
                },
                {
                    field: 'name',
                    title: '服务项名称',
                    sortable: true
                },

                {
                    field: 'originalPrice',
                    title: '服务的价格',
                    sortable: true
                },
                {
                    field: 'info',
                    title: '备注信息',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return $.table.tooltip(value, 0, "open");
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)"' +
                            ' onclick="addItem(\'' + row.id + '\')"><i class="fa fa-plus"></i></a>');
                        return actions.join(' ');
                    }
                }]
        };
        $.table.init(options);


    });

    // 保存操作
    function saveFun(){
        var statementId = [[${statement.id}]];
        //1 获取表格中所有数据
        var data= $('#statementItemTable').bootstrapTable('getData',false);
        $.each(data,function (index,item) {
            item.statementId = statementId;
        })

        data.push({"itemPrice" : $("#discountAmount").val() , "statementId" : statementId});
        console.log(data)
        // 发送ajax请求
        var config = {
            url: "/business/statementItem/saveItems",
            type: 'post',
            dataType: 'json',
            contentType:"application/json",
            data: JSON.stringify(data),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                // 解决方式1 : 成功以后吧表格中最后一条数据给删除
                // 解决方式2 : 直接去刷新表格让他重新去获取数据库中最新的数据
                $.table.refresh("statementItemTable");
                $.operate.ajaxSuccess(result);
            }
        };
        $.ajax(config)

    }




    function addItem(id){
        // id 单项的id
        //1 拿到当前点击这条数据
        var rs=$('#serviceItemTable').bootstrapTable('getRowByUniqueId',id);
        // console.log(rs);
        //2 把数据添加到左侧的表格中
        var newData = {itemId:rs.id ,itemName: rs.name ,itemPrice: rs.originalPrice,itemQuantity:1}

        //3 判断左侧表格中数据是否存在
        // 把数据查询出来看是否存在, 根据什么查询 , 根据id进行查询
        // 你能够拿到左侧表格id  , 但是可以拿到单项id  , 已知 一个结算单中单项id也是唯一的, 可以直接根据单项id去查询是数据
        var statementData=$('#statementItemTable').bootstrapTable('getRowByUniqueId',id);
        if(statementData){
            // 将数量进行加1 的操作
            $('#statementItemTable').bootstrapTable('updateCellByUniqueId', {
                id: id,
                field: 'itemQuantity',
                value: statementData.itemQuantity + 1
            })
        }else{
            $('#statementItemTable').bootstrapTable('append', newData);

        }
        disCountFun();
    }

    function decrItem(id){
        // 根据单项id去查询数据
        var statementData=$('#statementItemTable').bootstrapTable('getRowByUniqueId',id);
        console.log(statementData);
        // 判断数量是否大于1
        if(statementData.itemQuantity > 1){
            // 将数量进行加1 的操作
            $('#statementItemTable').bootstrapTable('updateCellByUniqueId', {
                id: id,
                field: 'itemQuantity',
                value: statementData.itemQuantity - 1
            })
        }else{
            // 删除这条数据
            $('#statementItemTable').bootstrapTable('removeByUniqueId',id);
        }
        disCountFun();
    }

    function disCountFun(){
        //1 拿到左侧表格中所有数据
        var data= $('#statementItemTable').bootstrapTable('getData',false);
        console.log(data)
        //2 循环遍历计算总金额
        var totalAmount = 0;
        $.each(data,function (index,item) {
            totalAmount += item.itemPrice * item.itemQuantity;
        })
        //3 拿到优惠金额
        var discountAmount = $("#discountAmount").val();
        if(discountAmount < 0 ){
            alert("111")
            $("#discountAmount").val(0);
            $("#actuallyPaid").html(totalAmount);
            return;
        }
        // 如果集合中没有元素应该让所有金额为0
        if(data.length == 0){
            $("#discountAmount").val(0);
            $("#totalAmount").html(0);
            $("#actuallyPaid").html(0);
            return;
        }
       // 如果优惠金额大于总金额 让折扣为0
        if(discountAmount > totalAmount){
            alert(2222)
            $("#discountAmount").val(0);
            return;
        }

        // 计算实付金额
        var realPrice = totalAmount - discountAmount;
        console.log(totalAmount)
        console.log(realPrice)
        // 进行赋值操作
        $("#totalAmount").html(totalAmount);
        $("#actuallyPaid").html(realPrice);

    }


</script>
</html>